package com.zhaoc.service.impl;

import com.zhaoc.dao.MenuRepository;
import com.zhaoc.dao.PermissionRepository;
import com.zhaoc.dao.RoleRepository;
import com.zhaoc.domain.system.Menu;
import com.zhaoc.domain.system.Permission;
import com.zhaoc.domain.system.Role;
import com.zhaoc.domain.system.User;
import com.zhaoc.service.IRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>title:com.zhaoc.service.impl</p>
 * date:2018/8/21 0021
 * time:18:04
 * author:赵成
 * user:13566
 */
@Service
@Transactional
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private PermissionRepository permissionRepository;

    @Autowired
    private MenuRepository menuRepository;

    @Override
    public List<Role> findByUser(User user) {
        //admin具有所有角色
        if (user.getUsername().equals("admin")){
        return roleRepository.findAll();
        }else {
            return roleRepository.findByUser(user.getId());
        }
    }

    //查询所有角色
    @Override
    public List<Role> findAll() {
        return roleRepository.findAll();
    }

    //添加角色
    @Override
    public void save(Role role, String[] permisssionTd, String menuIds) {
        //调用dao层保存角色
        roleRepository.save(role);

        //角色关联权限
        if (permisssionTd != null){
            for (String permission : permisssionTd) {
                Permission permission1 = permissionRepository.findOne(Integer.parseInt(permission));
                role.getPermissions().add(permission1);
            }
        }

        //角色关联菜单
        if (StringUtils.isNotBlank(menuIds)){
            String[] menuArray = menuIds.split(",");
            for (String menu1 : menuArray) {
                Menu menu = menuRepository.findOne(Integer.parseInt(menu1));
                role.getMenus().add(menu);
            }
        }

    }
}
